<template>
  <div class="weather">
    <div class="weather-block weather-day">
      <p class="day">{{ pageData?.main?.temp}} / {{ dayWeather?.wendu}} / {{ baiduData.now?.temp}}℃ <span class="temperature">{{ dayWeather1.type }}</span></p>
      <p><span class="temperature">{{ dayWeather1.low.split(' ')[1] }} - {{ dayWeather1.high.split(' ')[1]}}</span></p>
      <p>风向：<span class="temperature">{{ dayWeather1.fx }}</span> 风力：<span class="temperature">{{ dayWeather1.fl }}</span></p>
      <p>日出：<span class="temperature">{{ dayWeather1.sunrise }}</span> 日落：<span
          class="temperature">{{ dayWeather1.sunset }}</span></p>
      <p>湿度：<span class="temperature">{{ dayWeather.shidu || pageData.main.humidity }}</span></p>
      <p>PM2.5：<span class="temperature" style="margin-right: 20px;">{{ dayWeather.pm25 }}</span> PM10：<span
          class="temperature">{{ dayWeather.pm10 }}</span></p>
      <p>空气质量：<span class="temperature">{{ dayWeather.quality }}</span></p>
      <p>温馨提示：<span class="temperature">{{ dayWeather.ganmao }}</span></p>
    </div>
    <div class="weather-trend">
      <div class="trend-list">
<!--        <h3>日出日落趋势</h3>-->
        <div style="width: 700px;height: 200px" ref="myChart1" id="myChart1"></div>
      </div>
      <div class="trend-list">
<!--        <h3>天气趋势</h3>-->
        <div style="width: 700px;height: 200px" ref="myChart1" id="myChart2"></div>
      </div>
    </div>
    <div class="weather-lists">
      <div class="weather-block" v-for="item in weatherList">
        <p>{{ item.ymd }} {{item.week}}</p>
        <p>温度：<span class="temperature">{{ item.low.split(' ')[1] }} - {{ item.high.split(' ')[1] }}</span></p>
        <p style="font-size: 18px;">天气：<span class="temperature">{{ item.type }}</span> 风向：<span class="temperature">{{ item.fx }}</span> 风力：<span class="temperature">{{ item.fl }}</span></p>
        <p>日出：<span class="temperature">{{ item.sunrise }}</span> 日落：<span
          class="temperature">{{ item.sunset }}</span></p>
        <p><span class="temperature1">{{ item.notice }}</span></p>
      </div>
    </div>
  </div>
</template>

<script setup>
import {ref, computed, defineProps, nextTick} from 'vue'
import * as echarts from 'echarts'
import chinese from 'chinese-lunar'

const week = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']

const myChart1 = ref(null)
const props = defineProps({
  dayWeather: {
    type: Object,
    default: () => {
    }
  }
})
// console.log(2222, props.dayWeather)
const city = computed(() => props.dayWeather?.city)
const weatherList = computed(() => props.dayWeather?.forecast?.slice(1, 6))
const dayWeather1 = props.dayWeather?.forecast[0]
let pageData = {}, baiduData = {main: {now: ''}};

// 提取字符串中的数字，包括负数
const extractNumber = (str) => {
  const match = str.match(/-?\d+/);
  return match ? parseInt(match[0], 10) : null;
}

const getChart1 = () => {
  console.log(document.getElementById('myChart1'))
  const myChart = echarts.init(document.getElementById('myChart1'))
  const xAxisData = props.dayWeather.forecast.map(item => item.ymd)
  const highData = props.dayWeather.forecast.map(item => extractNumber(item.high))
  const lowData = props.dayWeather.forecast.map(item => extractNumber(item.low))
  const lowIndex = lowData.indexOf(Math.min(...lowData))
  const lowValue = lowData[lowIndex]
  // 配置图表选项
  const option = {
    title: {
      text: '15天温度趋势',
      textStyle: {
        color: '#eee'
      }
    },
    tooltip: {
      trigger: 'axis',
      formatter: function (params) {
        console.log(params)
        return `
          ${params[0].axisValue} ${week[new Date(params[0].axisValue).getDay()]}<br/>
          ${chinese.solarToLunar(new Date(params[0].axisValue), 'T A MD')}<br/>
          ${params[0].marker} ${params[0].seriesName} ${params[0].value}℃<br/>
          ${params[1].marker} ${params[1].seriesName} ${params[1].value}℃
        `
      }
    },
    legend: {
      textStyle: {
        color: '#fff'
      }
    },
    grid: {
      bottom: 20,
      left: 40,
      right: 40,
    },
    toolbox: {
      show: false,
      feature: {
        dataZoom: {
          yAxisIndex: 'none'
        },
        dataView: { readOnly: false },
        magicType: { type: ['line', 'bar'] },
        restore: {},
        saveAsImage: {}
      }
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: xAxisData,
      axisLine: {lineStyle: {color: '#fff'}},
      axisLabel: {
        formatter: function (value) {
          return echarts.format.formatTime('MM-dd', value)
        },
        interval: 0
      }
      // data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: '{value} °C'
      },
      axisLine: {lineStyle: {color: '#fff'}}
    },
    series: [
      {
        name: '高温',
        type: 'line',
        smooth: true,
        // data: [10, 11, 13, 11, 12, 12, 9],
        data: highData,
        markPoint: {
          data: [
            { type: 'max', name: 'Max' },
            { type: 'min', name: 'Min' }
          ]
        },
        markLine: {
          data: [{ type: 'average', name: 'Avg' }]
        }
      },
      {
        name: '低温',
        type: 'line',
        smooth: true,
        // data: [1, -2, 2, 5, 3, 2, 0],
        data: lowData,
        markPoint: {
          // data: [{ name: '周最低', value: lowValue, xAxis: lowIndex, yAxis: lowValue }]
          data: [
            { type: 'max', name: 'Max' },
            { type: 'min', name: 'Min' }
          ]
        },
        markLine: {
          data: [
            { type: 'average', name: 'Avg' },
            [
              {
                symbol: 'none',
                x: '90%',
                yAxis: 'max'
              },
              {
                symbol: 'circle',
                label: {
                  position: 'start',
                  formatter: 'Max'
                },
                type: 'max',
                name: '最高点'
              }
            ]
          ]
        }
      }
    ]
  }

  // 使用配置项和数据显示图表
  myChart.setOption(option)
}
const getChart2 = () => {
  const myChart = echarts.init(document.getElementById('myChart2'))
  const xAxisData = props.dayWeather.forecast.map(item => item.ymd)
  console.log('props.dayWeather',props.dayWeather)
  console.log('xAxisData',xAxisData)
  const year = new Date().getFullYear()
  const highData = props.dayWeather.forecast.map(item => new Date( item.ymd + ' ' + item.sunrise).getTime())
  const lowData = props.dayWeather.forecast.map(item => new Date(item.ymd + ' ' + item.sunset).getTime())
  console.log('highData', props.dayWeather.forecast.map(item => item.sunrise))
  console.log('lowData',  props.dayWeather.forecast.map(item => item.sunset))
  // 配置图表选项
  const option = {
    title: {
      text: '15天日出日落趋势',
      textStyle: {
        color: '#eee'
      }
    },
    tooltip: {
      trigger: 'axis',
      formatter: function (params) {
        console.log(params)
        return `
          ${params[0].axisValue} ${week[new Date(params[0].axisValue).getDay()]}<br/>
          ${chinese.solarToLunar(new Date(params[0].axisValue), 'T A MD')}<br/>
          ${params[0].marker} ${params[0].seriesName} ${echarts.format.formatTime('hh:mm', params[0].value)}<br/>
          ${params[1].marker} ${params[1].seriesName} ${echarts.format.formatTime('hh:mm', params[1].value)}
        `
      }
    },
    legend: {
      textStyle: {
        color: '#fff'
      }
    },
    grid: {
      bottom: 20,
      left: 40,
      right: 20,
    },
    toolbox: {
      show: false,
      feature: {
        dataZoom: {
          yAxisIndex: 'none'
        },
        dataView: { readOnly: false },
        magicType: { type: ['line', 'bar'] },
        restore: {},
        saveAsImage: {}
      }
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: xAxisData,
      axisLine: {lineStyle: {color: '#fff'}},
      axisLabel: {
        formatter: function (value) {
          return echarts.format.formatTime('MM-dd', value)
        },
        interval: 0
      }
    },
    yAxis: {
      type: 'category',
      axisLabel: {
        formatter: function (value) {
          const date = new Date(parseInt(value))
          console.log(2, date)
          return date.getHours() + ':' + date.getMinutes();
        }
      },
      axisLine: {lineStyle: {color: '#fff'}}
    },
    series: [
      {
        name: '日出',
        type: 'line',
        smooth: true,
        data: highData,
      },
      {
        name: '日落',
        type: 'line',
        smooth: true,
        data: lowData,
      }
    ]
  }

  // 使用配置项和数据显示图表
  myChart.setOption(option)
}


// const url = `https://api.openweathermap.org/data/2.5/weather?lon=116.3972&lat=39.9075&appid=d030ad783b9a7d12546e022d56815a7f&units=metric&lang=zh_cn&callback=test`
/* 百度天气api日次数5000 */
try {
  // const baiduUrl = `https://api.map.baidu.com/weather/v1/?district_id=110100&data_type=all&ak=6GrqtvsS80ywrqyXV3YcuIMBcNPVvnGF`
  // const baiduUrl = `http://127.0.0.1:3100/api/getWeather`
  const baiduUrl = `http://localhost:3100/api/getWeather?id=110`
  const baiduResponse = await fetch(baiduUrl)
  const data = await baiduResponse.json()
  baiduData = data.result
  getChart1()
  getChart2()
  // console.log('baiduData', baiduData)
} catch (e) {
  console.log('百度天气接口错误222', e)
}

try {
  const url = `https://api.openweathermap.org/data/2.5/weather?lon=116.3972&lat=39.9075&appid=d030ad783b9a7d12546e022d56815a7f&units=metric&lang=zh_cn`
  const response = await fetch(url)
  pageData = await response.json()
} catch (e) {
  console.log('openweathermap接口错误', e)
  pageData.main = {}
}

</script>

<style scoped>
.weather {
  position: fixed;
  width: 100%;
  bottom: 40px;
  left: 0;
  right: 0;
  color: #fff;
  line-height: 1;
  text-align: center;
  font-weight: 400;
}

.weather .weather-day {
  position: fixed;
  top: 10px;
  left: 10px;
  text-align: left;
  padding: 0 30px;
  background: rgba(0, 0, 0, 0.4);
}

.weather-day .day {
  font-weight: bold;
  font-size: 26px;
}

.weather-trend {
  display: flex;
  justify-content: space-between;
  padding: 10px 20px;
}
.trend-list {
  background: rgba(0, 0, 0, 0.4);
  padding: 10px;
  border-radius: 10px;
}

.weather-lists {
  display: flex;
  flex-wrap: nowrap;
  justify-content: space-between;
}

.weather-block {
  max-width: 365px;
  display: inline-block;
  padding: 0 20px;
  background: rgba(0, 0, 0, 0.4);
  border-radius: 20px;
  margin: 0 5px;
}

.temperature {
  font-weight: 600;
  line-height: 1;
}
</style>
